package com.pansoft.openplanet.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.pansoft.openplanet.R;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import pub.devrel.easypermissions.AfterPermissionGranted;

/**
 * 蓝牙通讯（ble）
 *
 * @author YQS
 */

public class BleMessageActivity extends TCBaseActivity implements View.OnClickListener {
    private static final String TAG = "BleMessageActivity";
    private TextView tvTitle;
    private TextView tvReconnect;
    private TextView tvStatus;
    private GifImageView ivImage;

    private BleDevice bleDevice;

    /* 需写入的地址*/
    private String address;

    /**
     * @param context
     * @param bleDevice 设备;
     * @param address   写入的地址
     */
    public static void start(Context context, BleDevice bleDevice, String address) {
        Intent starter = new Intent(context, BleMessageActivity.class);
        starter.putExtra("bleDevice", bleDevice);
        starter.putExtra("address", address);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_acitivty_blt_message);
        bleDevice = (BleDevice) getIntent().getParcelableExtra("bleDevice");
        address = getIntent().getStringExtra("address");
        initView();
        initAdapter();
        checkBltPermission();
        initData();
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance().disconnect(bleDevice);
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvStatus = (TextView) findViewById(R.id.tv_status);
        ivImage = (GifImageView) findViewById(R.id.iv_image);
        tvReconnect = (TextView) findViewById(R.id.tv_save);
        tvReconnect.setOnClickListener(this);
    }

    private void initAdapter() {

    }

    private void initData() {
        tvTitle.setText(R.string.chat_my_device);
        tvReconnect.setText(R.string.common_text_device_reconnect);
        try {
            GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.ble_connecting);
            gifDrawable.setLoopCount(0);
            ivImage.setImageDrawable(gifDrawable);
        } catch (Exception e) {
            e.printStackTrace();
        }

        connectDevice();
    }

    //检查蓝牙权限
    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_LOCATION)
    private void checkBltPermission() {
        //检查是否有蓝牙
        if (!BleManager.getInstance().isSupportBle()) {

            new AlertDialog.Builder(this).setTitle(R.string.common_text_hint).setMessage(R.string.common_text_bluetooth_not_support)
                    .setCancelable(false).setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).show();
            return;
        }


        if (!EasyPermissionUtils.checkLocationPermission()) {
            EasyPermissionUtils.requestLocationPermission(this);
        } else {
            //检查蓝牙是否打开
            if (!BleManager.getInstance().isBlueEnable()) {
                new AlertDialog.Builder(this).setTitle(R.string.common_text_hint).setMessage(R.string.common_text_please_open_bluetooth)
                        .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                startActivityForResult(intent, 100);
                            }
                        }).show();

                //this.startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));

            }
        }
    }


    /**
     * 连接选中的设备
     */
    private void connectDevice() {
        if (BleManager.getInstance().isConnected(bleDevice)) {
            ToastUtil.showToast(this, R.string.common_text_device_has_connected);
            return;
        }
        //1.取消连接的别的设备

        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                tvStatus.setText(R.string.common_text_device_connecting);
                showLoading(R.string.common_text_device_connecting);
                tvReconnect.setVisibility(View.GONE);
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                dismissLoading();
                tvStatus.setText(R.string.common_text_bluetooth_connect_fail);
                tvReconnect.setVisibility(View.VISIBLE);
                ToastUtil.showToast(BleMessageActivity.this, R.string.common_text_bluetooth_connect_fail);
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                dismissLoading();
                tvStatus.setText(R.string.common_text_device_has_connected);
                tvReconnect.setVisibility(View.GONE);
                ToastUtil.showToast(BleMessageActivity.this, R.string.common_text_bluetooth_connect_success);

            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                dismissLoading();
                tvStatus.setText(R.string.common_text_bluetooth_disconnect);
                tvReconnect.setVisibility(View.VISIBLE);
                ToastUtil.showToast(BleMessageActivity.this, R.string.common_text_bluetooth_disconnect);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            checkBltPermission();
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        }
    }


}